<template>
    <div class="list-com">
        <el-popover popper-class="com-popover" v-for="(item, index) in state.list" :key="index" width="344" trigger="hover"
            placement="top-start" :offset="10" popper-style="border-radius:0;" transition="aaa" :show-arrow="true">
            <template #reference>
                <span class="card-label">{{ item.label }}</span>
            </template>
            <el-row :gutter="10" class="card-list">
                <el-col :span="8" v-for="(card, cardIndex) in item.cards" :key="card._id" class="card-item">
                    <el-image class="card-item-image" :src="card.image"
                        @mousedown="handleDragendShape($event, card, index, cardIndex)" :id="'card' + index + cardIndex"
                        fit="cover" />
                    <div class="card-item-text">{{ card.name }}</div>
                </el-col>
            </el-row>
        </el-popover>
        <!-- 滑块 -->
        <img class="slider" :src="slider.url" :style="getSliderStyle(slider)" alt="" />
    </div>
</template>
<script setup>
import { reactive } from 'vue'
import { userCardStore, getBestPos } from '../../store/userCardStore'
import { throttleFrame, GetQueryString } from '../../utils/utils'
import getInitCard from '../Editor/card.config'
import { queryAssembly_sort } from '/@/api/assembly'
import { queryPage } from '/@/api/page'
import { getComData, addExternalEle } from '/@/utils/common'
import axios from 'axios'
import { cloneDeep } from 'lodash'
import group from '../../../../components/group.vue'
const cardStore = userCardStore()



// 缓存cards
const cardsMap = {}
// 组件映射
const comMap = {}
const state = reactive({
    list: [],
})
queryAssembly_sort().then((result) => {
    const dataMap = {}
    result.forEach((item) => {
        !dataMap[item.classify_name] && (dataMap[item.classify_name] = [])
        const com = {
            name: item.name,
            url: `https://${item.CdnDomain}/cards/${item.name_es}/${item.version}/index.js`,
            panelUrl: `https://${item.CdnDomain}/cards/${item.name_es}/${item.version}/panel.js`,
            cardJsonUrl: `https://${item.CdnDomain}/cards/${item.name_es}/${item.version}/card.json`,
            image: item.icon,
            name_es: item.name_es,
            assembly_sort_id: item._id,
        }
        comMap[item.name_es] = com
        dataMap[item.classify_name].push(com)
    })
    const arr = []
    for (let key in dataMap) {
        arr.push({
            label: key,
            cards: dataMap[key],
        })
    }
    state.list = arr

    // 获取页面内容
    const pid = GetQueryString('pid')
    if (pid) {
        queryPage(pid).then(async res => {
            const page = res[0]
            if (!page) return
            const content = page.content
            // 添加卡片
            const { cards, editor, layout, layouts = [], name, icon, padding } = content
            Object.assign(cardStore, { icon, layout, layouts, name, padding })
            const { width, height, backgroundColor, externals } = editor
            Object.assign(cardStore.editor, { width, height, backgroundColor })
            cardStore.editor = editor

            // 
            const pos = getBestPos(cardStore.editor.width, cardStore.editor.height)
            cardStore.setEditorTransform(pos, 'touch')

            // 加载外部文件
            await addExternalEle(externals)

            // 组装普通 卡片
            const assemble = (card, callback) => {
                const detail = comMap[card.name_es]
                card.style.top = parseFloat(card.style.top)
                card.style.left = parseFloat(card.style.left)
                card.style.width = parseFloat(card.style.width)
                card.style.height = parseFloat(card.style.height)
                const newCard = getInitCard({
                    _id: Math.random(),
                    style: card.style,
                    url: card.url,
                    name: card.name,
                    name_es: card.name_es,
                    assembly_sort_id: detail.assembly_sort_id,
                    panelUrl: detail.panelUrl,
                    cardJson: card.cardJson,
                    comData: Array.isArray(card.cardJson.staticData) ? [] : {},
                    image: detail.image,
                    // name_es: card.name_es,
                    // component: text
                })
                getComData(card.cardJson).then(data => {
                    Object.assign(newCard.comData, data)
                    cardStore.refresh(true)
                })
                return newCard
            }
            const assembleGroup = (card) => {
                card.style.top = parseFloat(card.style.top)
                card.style.left = parseFloat(card.style.left)
                card.style.width = parseFloat(card.style.width)
                card.style.height = parseFloat(card.style.height)
                const newCard = getInitCard({
                    _id: Math.random(),
                    style: card.style,
                    group: true,
                    component: group,
                    name: card.name,
                    cardJson: card.cardJson,
                })
                newCard.cardJson.initProp.cards && card.cardJson.initProp.cards.forEach((item, index) => {
                    let newItem
                    if (item.group) {
                        newItem = assembleGroup(item)
                    } else {
                        newItem = assemble(item, () => {
                            newCard.cardJson.initProp.cards = newCard.cardJson.initProp.cards.slice(0)
                        })
                    }
                    newCard.cardJson.initProp.cards[index] = newItem
                })
                return newCard
            }

            cards.forEach(card => {
                let newCard
                if (card.group) {
                    newCard = assembleGroup(card)
                } else {
                    newCard = assemble(card)
                }
                cardStore.addCom(
                    newCard
                )
            })
        })
    }
})

const slider = reactive({
    url: '',
    top: 0,
    left: 0,
    show: false,
})
const getSliderStyle = (style) => {
    let str = ''
    const filters = ['top', 'left', 'width', 'height', 'show']
    Object.keys(style).forEach((key) => {
        if (filters.includes(key)) {
            if (key === 'show') {
                str += `display: ${style.show ? 'block' : 'none'};`
            } else {
                str += `${key}:${style[key]}px;`
            }
        }
    })
    return str
}
/**
 * 拖动
 */
const handleDragendShape = (e, card, index, cardIndex) => {
    e.preventDefault()

    e.stopPropagation()
    const img = document.getElementById(`card${index}${cardIndex}`)
    let { x: left, y: top, width, height } = img.getBoundingClientRect()
    function setSliderStyle(style) {
        Object.keys(style).forEach((key) => {
            slider[key] = style[key]
        })
    }
    setSliderStyle({
        top,
        left,
        width,
        height,
        url: card.image,
        show: true,
    })
    const startY = e.clientY
    const startX = e.clientX
    // 如果直接修改属性，值的类型会变为字符串，所以要转为数值型
    const startTop = top
    const startLeft = left

    // 如果元素没有移动，则不保存快照
    const move = throttleFrame((moveEvent) => {
        const curX = moveEvent.clientX
        const curY = moveEvent.clientY
        top = curY - startY + startTop
        left = curX - startX + startLeft

        // // 修改当前组件样式
        setSliderStyle({ top, left })
    })
    const up = async (e) => {
        document.removeEventListener('mousemove', move)
        document.removeEventListener('mouseup', up)
        setSliderStyle({
            show: false,
        })
        const { x, y } = e
        let { left, top, width, height, scale } = cardStore.editor
        top = top + (height - height * scale) / 2
        left = left + (width - width * scale) / 2
        // x > left && x < left + width && y > top && y < top + height
        if (true) {
            // 获取card.json
            if (!cardsMap[card.name_es]) {
                const res = await axios.get(card.cardJsonUrl)
                cardsMap[card.name_es] = res.data
            } else {
                await new Promise(r => {
                    setTimeout(() => {
                        r()
                    }, 20);
                })
            }
            const cardJson = cloneDeep(cardsMap[card.name_es])
            const { width: cardWidth, height: cardHeight } = cardJson.config || {
                width: 200,
                height: 50,
            }
            const newCard = getInitCard({
                style: {
                    top: parseInt((y - top) / cardStore.editor.scale),
                    left: parseInt((x - left) / cardStore.editor.scale),
                    width: cardWidth,
                    height: cardHeight,
                },
                url: card.url,
                panelUrl: card.panelUrl,
                cardJsonUrl: card.cardJsonUrl,
                name: card.name,
                image: card.image,
                cardJson,
                comData: Array.isArray(cardJson.staticData) ? [] : {},
                name_es: card.name_es,
                assembly_sort_id: card.assembly_sort_id,
                // component: text
            })
            getComData(cardJson).then(data => {
                newCard.comData = data
            })

            cardStore.addCom(
                newCard
            )
        }
    }
    document.addEventListener('mousemove', move)
    document.addEventListener('mouseup', up)
}
</script>
<style lang="less" scoped>
.list-com {
    display: flex;
    align-items: center;
    font-size: 14px;
}

.card-label {
    background-color: #fff;
    box-shadow: rgba(0, 0, 0, 0.12) 0px 0px 12px 0px;
    border-radius: 4px;
    color: rgb(0, 0, 0);
    font-size: 14px;
    padding: 0 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    line-height: 40px;
    height: 40px;
    cursor: pointer;
    opacity: 0.7;
    margin-right: 16px;

    &:hover {
        opacity: 1;
    }
}

.card-list {
    max-height: 500px;
    overflow-y: auto;
}

.card-item {
    .card-item-image {
        width: 100%;
        height: 60px;
        cursor: grab;
    }

    .card-item-text {
        color: #000;
        opacity: 0.7;
        font-size: 12px;
        text-align: center;
    }

    &:hover {
        .card-item-text {
            opacity: 1;
        }

        .card-item-image {
            // border: 1px solid #3a89fe;
        }
    }
}

.slider {
    position: fixed;
    z-index: 9999;
    object-fit: cover;
}
</style>
<style lang="less">
.com-popover {
    border: none !important;

    .el-popper__arrow::before {
        border: none !important;
    }
}
</style>
